package matchs

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/matchs/request"
	"github.com/flipped-aurora/gin-vue-admin/server/service/matchs"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

type AskApi struct{}

// CreateAskTask 创建问问任务
// @Tags MatchAsk
// @Summary 创建问问任务
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CreateAskTask true "创建问问任务请求参数"
// @Success 200 {object} response.Response{data=map[string]uint64,msg=string} "创建成功，返回ask_id"
// @Router /api/ask [post]
func (a *AskApi) CreateAskTask(c *gin.Context) {
	var req request.CreateAskTask
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数绑定失败: "+err.Error(), c)
		return
	}

	// 从JWT中获取用户ID
	userId := utils.GetUserID(c)

	// 调用服务层创建问问任务
	askId, err := matchs.AskServiceApp.CreateAskTask(c.Request.Context(), uint64(userId), req.Content, req.TargetProfessionalIDs, req.IsAnonymous)
	if err != nil {
		global.GVA_LOG.Error("创建问问任务失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 返回成功响应，包含ask_id
	response.OkWithDetailed(map[string]uint{"ask_id": askId}, "创建成功", c)
}

// GetUserAskTaskListHandler 获取用户问问任务列表
// @Tags MatchAsk
// @Summary 获取用户问问任务列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param status query int false "任务状态（0-待匹配 1-匹配中 2-已收到回复 3-已接受回复 4-已结束 5-已超时）"
// @Param page query int true "页码"
// @Param size query int true "每页条数"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功，返回任务列表和总数"
// @Router /api/v1/match/ask/list [get]
func (a *AskApi) GetUserAskTaskListHandler(c *gin.Context) {
	// 绑定查询参数
	var req request.GetAskTaskListReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage("参数绑定失败: "+err.Error(), c)
		return
	}

	// 从JWT中获取用户ID
	userId := utils.GetUserID(c)

	// 调用服务层获取任务列表
	taskList, total, err := matchs.AskServiceApp.GetUserAskTaskList(c.Request.Context(), uint64(userId), req.Status, req.Page, req.PageSize)
	if err != nil {
		global.GVA_LOG.Error("获取问问任务列表失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 封装分页结果并返回
	response.OkWithDetailed(response.PageResult{
		List:     taskList,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, "获取成功", c)
}

// GetAskTaskDetailHandler 获取单个问问任务详情
// @Summary 获取单个问问任务详情
// @Description 获取单个问问任务详情，包含回复列表
// @Tags 问问模块
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param ask_id query uint true "问问任务ID" binding:"required,min=1"
// @Success 200 {object} response.Response{data=response.AskTaskDetailVO,msg=string} "获取成功，返回任务详情和回复列表"
// @Router /api/v1/match/ask/detail [get]
func (a *AskApi) GetAskTaskDetailHandler(c *gin.Context) {
	// 定义请求参数结构体
	type GetAskTaskDetailReq struct {
		AskID uint `form:"ask_id" binding:"required,min=1"`
	}

	var req GetAskTaskDetailReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 获取当前登录用户ID
	userId := utils.GetUserID(c)

	// 调用Service层方法
	detail, err := matchs.AskServiceApp.GetAskTaskDetail(c, userId, req.AskID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 返回成功响应
	response.OkWithDetailed(detail, "获取详情成功", c)
}

// ReplyAskTaskHandler 回复问问任务
func (a *AskApi) ReplyAskTaskHandler(c *gin.Context) {
	// 1. 绑定请求参数
	var req request.ReplyAskTaskReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}

	// 2. 获取当前登录用户ID
	userId := utils.GetUserID(c)

	// 3. 调用Service层函数
	replyId, createdAt, err := matchs.AskServiceApp.ReplyAskTask(c.Request.Context(), userId, &req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 4. 返回成功响应
	responseData := gin.H{
		"reply_id":   replyId,
		"created_at": createdAt,
	}
	response.OkWithData(responseData, c)
}

// AcceptAskReplyHandler 接受问问回复（标记最佳回复）
// @Tags MatchAsk
// @Summary 接受问问回复
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.AcceptAskReplyReq true "接受回复请求参数"
// @Success 200 {object} response.Response{msg=string} "接受成功"
// @Router /api/v1/match/ask/accept-reply [post]
func (a *AskApi) AcceptAskReplyHandler(c *gin.Context) {
	// 1. 绑定请求参数
	var req request.AcceptAskReplyReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage("参数错误：请传入有效的任务ID和回复ID", c)
		return
	}

	// 2. 获取当前登录用户ID
	userId := utils.GetUserID(c)

	// 3. 调用Service层函数
	err := matchs.AskServiceApp.AcceptAskReply(c.Request.Context(), uint64(userId), &req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 4. 返回成功响应
	response.OkWithMessage("已接受该回复，任务已完成", c)
}

// GetReceivedAskTaskListHandler 获取接收到的问问任务列表
// @Tags 匹配-问问模块
// @Summary 获取接收到的问问任务列表
// @Security ApiKeyAuth
// @Produce  json
// @Param status query string false "状态筛选（unreplied/replied/selected/expired）"
// @Param page query int false "页码，默认1"
// @Param pageSize query int false "每页条数，默认20，最大50"
// @Success 200 {object} response.PageResult{data=[]map[string]interface{}} "查询成功"
// @Router /matchs/ask/received-list [get]
func (a *AskApi) GetReceivedAskTaskListHandler(c *gin.Context) {
	// 获取查询参数
	statusFilter := c.Query("status")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))

	// 参数校验
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 50 {
		pageSize = 20
	}

	// 状态筛选参数校验
	validStatuses := map[string]bool{
		"":          true,
		"unreplied": true,
		"replied":   true,
		"selected":  true,
		"expired":   true,
	}
	if !validStatuses[statusFilter] {
		response.FailWithMessage("无效的状态筛选参数", c)
		return
	}

	// 获取当前用户ID
	userId := utils.GetUserID(c)

	// 调用服务层查询
	results, total, err := matchs.AskServiceApp.GetReceivedAskTaskList(context.Background(), uint64(userId), statusFilter, page, pageSize)
	if err != nil {
		response.FailWithMessage("查询失败: "+err.Error(), c)
		return
	}

	// 返回分页结果
	response.OkWithDetailed(response.PageResult{
		List:     results,
		Total:    total,
		Page:     page,
		PageSize: pageSize,
	}, "查询成功", c)
}
